package com.max.common.task;

import java.util.Iterator;
import java.util.List;
import java.util.TimerTask;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * 项目名称:max-project-graphics
 * 文件名称:WatchTask.java
 * 文件描述:
 * 创建人员:chenyibo
 * 创建时间:2013-1-29 下午03:08:15
 * 修改人员:chenyibo
 * 修改时间:2013-1-29 下午03:08:15
 * 修改备注:
 * @version V1.0
 */
public class WatchTask extends TimerTask
{

	private static Log log = LogFactory.getLog("task");
	
    // 定时任务管理器
    private static final AsyTaskManager taskManager = AsyTaskManager.getInstance();

    private static WatchTask instance = null;
    
    public static synchronized WatchTask getInstance() 
    {
        if (instance == null)
        	instance = new WatchTask();
        
        return instance;
    }
    
    public void run()
    {   
        // AsyTaskManager的任务集合备份
        final List<BaseTimerTask> allTask = AsyTaskManager.getInstance().getAllTask();
        
        try{
            for (Iterator<BaseTimerTask> iter = allTask.iterator(); iter.hasNext();)
            {
                BaseTimerTask btt = iter.next();

                // 该任务处于正在执行状态并且为监控任务
                if (!btt.isExecuting() || !btt.isMonitor())
                	continue;
            
                final boolean runOverTime = (System.currentTimeMillis() 
                		- btt.getLastRunTime()) > btt.getMaxRunTime() * 1000;

                if (runOverTime)
                {
                    log.info("The task [" + btt.getTaskName() + "] running exceeds ["
                            + btt.getMaxRunTime() + "] minutes and will be reschedualed.");
                
                    BaseTimerTask copy = btt.copy(); // 复制任务
                    copy.setExecutingFlag(false);

                    // 取消原任务。重新规划新任务。注意这样并不能阻止正在执行的任务。
                    synchronized (taskManager)
                    {
                        taskManager.cancelTask(btt);
                        taskManager.schedualTask(copy);
                    }
                }
            }
        }
        catch(Exception ex)
        {
        	ex.printStackTrace();
        	log.info("The watch task running throw Exception!"+ex.getMessage());
        }
        catch(Throwable thex)
        {
        	thex.printStackTrace();
        	log.info("The watch task running throw Throwable Exception!"+thex.getMessage());
        }
    }
}
